package com.qst.action.TestPersonnel;

import com.qst.BaseServlet;
import com.qst.ExamException;
import com.qst.RequestUtil;
import com.qst.WebUtil;
import com.qst.dao.DAOFactory;
import com.qst.dao.UserDao;
import com.qst.entity.TestPersonnel;
import com.qst.entity.User;
import com.qst.service.TestPersonnelService;
import com.qst.service.impl.ServiceFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebServlet("/testPersonnel/add.action")
public class AddServlet extends BaseServlet {
    private TestPersonnelService testPersonnelService = ServiceFactory
            .getService(TestPersonnelService.class);
    private UserDao dao = DAOFactory.getDao(UserDao.class);
    @Override
    protected void doAction(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = new User();
        req.getParameter("");
        user.setId(RequestUtil.getInt(req, "id"));
        user.setLogin(RequestUtil.getString(req, "login"));
        user.setPasswd(User.PASSWORD);
        user.setName(RequestUtil.getString(req, "name"));
        user.setType(RequestUtil.getInt(req, "type"));
        user.setStatus(RequestUtil.getInt(req, "status"));
        TestPersonnel s = new TestPersonnel();
        s.setUser(user);
        s.setGender(RequestUtil.getString(req, "gender"));
        s.setPhone(RequestUtil.getString(req, "login"));
        s.setTeamId(RequestUtil.getInt(req, "teamId"));
        s.setBirthDate(RequestUtil.getDate(req, "birthDate"));
        try {
            User login = dao.findByLogin(s.getPhone());
            if(login != null){
                addMessage(req, "该手机号已经存在！");
                int teamId=RequestUtil.getInt(req, "teamId");
                req.setAttribute("teamId", teamId);
                WebUtil.forward(req,resp,"/testPersonnel/create.jsp");
            }else{
                testPersonnelService.addTestPersonnel(s);
                addMessage(req, "参测人员添加成功");
                WebUtil.redirect(req, resp, "/testPersonnel/select.action?teamId="+s.getTeamId());}
        } catch (ExamException ex) {
            req.setAttribute("user", user);
            addError(req, ex.getMessage());
            WebUtil.forward(req, resp, "/testPersonnel/create.jsp");
        }
    }
}
